package com.jhinwins.equipmenteb.equipmentebserver.auth;

import com.jhinwins.equipmenteb.equipmentebserver.entity.UserBean;
import com.jhinwins.equipmenteb.equipmentebserver.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

//@Configuration
public class ShiroCfg {

    @Bean
    public ShiroFilterFactoryBean getFilterCfg(SecurityManager securityManager) {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);

        filterFactoryBean.setLoginUrl("/user/unlogin");

        Map<String, String> filterChain = new HashMap<>();

        //anon:不必验证就能访问   authc:需要登录才能访问
//        filterChain.put("/*", "anon");
        filterChain.put("/user/login", "anon");

        //配置注销url
        filterChain.put("/logout", "logout");

        //配置需要登录才能访问的url
        filterChain.put("/products/*", "authc");

        filterFactoryBean.setFilterChainDefinitionMap(filterChain);

        return filterFactoryBean;
    }

    @Bean
    public SecurityManager getSecurityManager(Realm realm) {
        return new DefaultWebSecurityManager(realm);
    }

}

@Service
class MyRealm extends AuthenticatingRealm {

    private UserService userService;

    @Autowired
    public MyRealm(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        UserBean userBean = Optional.of(userService.userExistence(usernamePasswordToken.getUsername())).orElseThrow(UnknownAccountException::new);
        return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), userBean.getPassword(), getName());
    }
}